package wang.z.component;

import wang.z.JFrame.loginFrm;
import wang.z.model.ResultInfo;
import wang.z.net.FailListener;
import wang.z.net.PostUtils;
import wang.z.net.SuccessListener;
import wang.z.utils.JsonUtils;
import wang.z.utils.PathUtils;
import wang.z.utils.ResultInfoData2Vector;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import static javax.swing.JTable.AUTO_RESIZE_OFF;

/**
 * @author like
 * @date 2022/12/12 23:51
 * @Description TODO
 */
public class UserUpdate {
    private JPanel panel_1 = new JPanel();//表格
    private DefaultTableModel BookModel;//模型表格
    private JTable BookTable;//表格

    private Vector<Vector> bookDate = new Vector<Vector>();//书数据
    private JTextField textField_1;//编号
    private JTextField textField_2;//书名
    private JTextField textField_3;//作者
    private JTextField textField_4;//价格
    private JPanel panel_2;
    private JPanel panel = new JPanel();
    private JTextField textField;//查询输入框
    private JButton button_1;//查询按钮、
    private JLabel label;
    private JFrame jf = null;

    String UserId;
    private JComboBox comboBox;//男女
    public UserUpdate(JFrame jf) throws IOException {


        this.jf = jf;
        panel.setLayout(null);
        panel.setBorder(new TitledBorder(null,
                "书籍查询", TitledBorder.LEADING, TitledBorder.TOP,
                null, new Color(255, 0, 0)));
        panel.setBounds(20, 2, 541, 70);
        textField = new JTextField();
        textField.setColumns(10);
        textField.setBounds(152, 23, 135, 27);
        panel.add(textField);
        button_1 = new JButton("查询");

        button_1.setFont(new Font("幼圆", Font.BOLD, 16));
        button_1.setBounds(300, 20, 93, 33);
        panel.add(button_1);
        label = new JLabel();
        label.setFont(new Font("幼圆", Font.BOLD, 15));
        label.setBounds(23, 26, 109, 24);

        panel.add(label);
        Map<String, String> params = new HashMap<String, String>();
        params.put("text","");

        button_1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Map<String, String> params1 = new HashMap<>();
                String text = textField.getText().trim();
                params1.put("text", text);
                likeDate(params1);
            }
        });


        panel_1.setLayout(null);
        panel_1.setBorder(new TitledBorder(null, "数据信息", TitledBorder.LEADING, TitledBorder.TOP,
                null, new Color(255, 0, 0)));
        panel_1.setBounds(20, 70, 541, 195);
        /*做一个表头栏数据  一维数组 * */
        String[] title = {"编号", "用户名", "密码", "性别", "电话"};
        Vector BookTitle = new Vector();
        for (String i : title) {
            BookTitle.add(i);
        }
        /*具体的各栏行记录 先用空的二维数组占位*/
        bookDate = new Vector<Vector>();

        BookModel = new DefaultTableModel(bookDate, BookTitle);
        BookTable = new JTable(BookModel) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        BookTable.getSelectionModel().setSelectionMode(AUTO_RESIZE_OFF);

        panel_1.setLayout(null);
        JScrollPane jscrollpane = new JScrollPane();
        jscrollpane.setBounds(20, 20, 496, 154);
        jscrollpane.setViewportView(BookTable);
        panel_1.add(jscrollpane);
        likeDate(params);
        BookTable.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {

                int selectedRow = BookTable.getSelectedRow();
                String id = BookTable.getValueAt(selectedRow, 0).toString();
                String username = BookTable.getValueAt(selectedRow, 1).toString();
                String password = BookTable.getValueAt(selectedRow, 2).toString();
                String phone = BookTable.getValueAt(selectedRow, 4).toString();
                String sex = BookTable.getValueAt(selectedRow, 3).toString();
                textField_1.setText(id);
                textField_2.setText(username);
                textField_3.setText(password);
                textField_4.setText(phone);
                if (sex.equals("女")) {
                    comboBox.setSelectedIndex(1);
                }
                UserId = id;

            }

            @Override
            public void mousePressed(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }
        });
        /**
         *
         */

        panel_2 = new JPanel();
        panel_2.setBorder(new TitledBorder(null,
                "修改", TitledBorder.LEADING, TitledBorder.TOP,
                null, new Color(250, 0, 0)));
        panel_2.setBounds(20, 270, 541, 195);

        panel_2.setLayout(null);
        JLabel label = new JLabel("编号：");
        label.setFont(new Font("幼圆", Font.BOLD, 14));
        label.setBounds(49, 30, 48, 34);
        panel_2.add(label);
        textField_1 = new JTextField();
        textField_1.setColumns(10);
        textField_1.setBounds(103, 37, 66, 21);
        panel_2.add(textField_1);
        JLabel label_1 = new JLabel("用户名：");
        label_1.setFont(new Font("幼圆", Font.BOLD, 14));
        label_1.setBounds(187, 30, 66, 34);
        panel_2.add(label_1);
        textField_2 = new JTextField();
        textField_2.setColumns(10);
        textField_2.setBounds(259, 37, 93, 21);
        panel_2.add(textField_2);
        JLabel label_2 = new JLabel("密码：");
        label_2.setFont(new Font("幼圆", Font.BOLD, 14));
        label_2.setBounds(383, 30, 48, 34);
        panel_2.add(label_2);
        textField_3 = new JTextField();
        textField_3.setColumns(10);
        textField_3.setBounds(437, 37, 93, 21);
        panel_2.add(textField_3);
        JLabel label_3 = new JLabel("性别：");
        label_3.setFont(new Font("幼圆", Font.BOLD, 14));
        label_3.setBounds(49, 74, 48, 34);
        comboBox = new JComboBox();
        comboBox.setFont(new Font("幼圆", Font.BOLD, 15));
        comboBox.setBounds(103, 81, 66, 21);
        comboBox.addItem("男");
        comboBox.addItem("女");
        panel_2.add(label_3);
        panel_2.add(comboBox);
        JLabel label_4 = new JLabel("手机号：");
        label_4.setFont(new Font("幼圆", Font.BOLD, 14));
        label_4.setBounds(187, 74, 66, 34);
        panel_2.add(label_4);
        textField_4 = new JTextField();
        textField_4.setColumns(10);
        textField_4.setBounds(259, 81, 93, 21);
        panel_2.add(textField_4);

        JButton btnNewButton_1 = new JButton("修改");
        btnNewButton_1.setBounds(422, 74, 87, 34);
        btnNewButton_1.setFont(new Font("幼圆", Font.BOLD, 14));
        btnNewButton_1.setBackground(new Color(255,165,0));
        btnNewButton_1.setFocusPainted(false);
        panel_2.add(btnNewButton_1);
        btnNewButton_1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = BookTable.getSelectedRow();//如果有选中的条目，则返回条目的行号，如果没有选中，那么返回-1

                if (selectedRow == -1) {
                    JOptionPane.showMessageDialog(jf, "请选择要修改的条目！");
                    return;
                }

                //防止误操作
                int result = JOptionPane.showConfirmDialog(jf, "确认要修改选中的条目吗？", "确认修改", JOptionPane.YES_NO_OPTION);
                if (result != JOptionPane.YES_OPTION) {
                    return;
                }
                Map<String ,String> paramsIn = new HashMap<>();
                String id = textField_1.getText().trim();
                String username = textField_2.getText().trim();
                String password = textField_3.getText().trim();
                String phone = textField_4.getText().trim();
                String sex =(String) comboBox.getSelectedItem();
                String role =bookDate.get(selectedRow).get(5).toString();
                paramsIn.put("username",username);
                paramsIn.put("id",id);
                paramsIn.put("password",password);
                paramsIn.put("phone",phone);
                paramsIn.put("sex",sex);
                paramsIn.put("UserId",UserId);
                paramsIn.put("role",role);
                PostUtils.postWithParams("http://localhost:8080/user/UpdateUser", paramsIn,new SuccessListener() {
                            //请求发送成功，服务器正常响应，会执行这里
                            @Override
                            public void success(String result) throws IOException {//result参数就是服务器响应回来的json字符串
                                ResultInfo info = JsonUtils.parseResult(result);
                                //判断info中的flag标记
                                if (info.isFlag()) {
                                    JOptionPane.showMessageDialog(jf, info.getMessage());
                                    likeDate(params);
                                } else {
                                    JOptionPane.showMessageDialog(jf, info.getMessage());
                                    if(info.getMessage().equals("用户尚未登录")){
                                        new loginFrm().init();
                                        jf.dispose();
                                    }
                                }
                            }
                        }
                        , new FailListener() {
                            //当该请求发送失败后会执行这个方法
                            @Override
                            public void fail() {
                                JOptionPane.showMessageDialog(jf, "传入的数据有误或者网路问题，请检查");
                            }
                        }
                );
            }
        });
        jf.add(panel_1);
        jf.add(panel_2);
        jf.add(panel);
        BackGroundPanel jPanel = new BackGroundPanel(ImageIO.read(new File(PathUtils.getRealPath("library.jpg"))));
        jPanel.setBounds(500,300,700,500);
        jf.add(jPanel);
    }


    public void likeDate(Map<String, String> params) {
        PostUtils.postWithParams("http://localhost:8080/user/getbylike", params, new SuccessListener() {
            @Override
            public void success(String result) throws IOException {
                ResultInfo info = JsonUtils.parseResult(result);
                if (info.isFlag()) {
                    //消息转换
                    Vector<Vector> vectors = ResultInfoData2Vector.convertResultInfoData2Vector(info);
                    //清空tableData的数据
                    bookDate.clear();
                    for (Vector vector : vectors) {
                        vector.add(vector.get(3));
                        vector.remove(3);
                        bookDate.add(vector);
                    }
                    //刷新表格
                    BookModel.fireTableDataChanged();
                } else {
                    JOptionPane.showMessageDialog(jf, info.getMessage());
                    if(info.getMessage().equals("用户尚未登录")){
                        new loginFrm().init();
                        jf.dispose();
                    }
                }
            }
        }, new FailListener() {
            @Override
            public void fail() {
                JOptionPane.showMessageDialog(jf, "网络异常，请稍后重试");
            }
        });
    }



}
